from odoo import fields, models, api
from odoo.exceptions import UserError
import base64
import csv
from io import StringIO
from ...functions.rp_backdoor_deal_20231120 import RPBackdoorDeal231120 as Deal1
from ...functions.rp_backdoor_deal_20240109 import RpBackdoorDeal20230109 as Deal2

province_city_county_selection = [('1', 'last'), ('3', 'level_1'), ('4', 'level_2'), ('5', 'level_3'), ('6', 'level_4'), ('7', 'level_5')]


class RPBackdoorTran(models.TransientModel):
    _name = 'rp.backdoor.tran'
    _description = "后门程序瞬态"
    _rec_name = "rpb_code"

    def _default_auto_rpb_code(self):
        records = self.env['rp.backdoor.tran'].search([])
        return "RPB" + str(len(records) + 1).zfill(3)

    rpb_code = fields.Char(string='索引码', default=_default_auto_rpb_code, index=True, copy=False, readonly=True)
    create_datetime = fields.Datetime(string='当前时间', default=fields.Datetime.now, copy=False, readonly=True)
    user_id = fields.Many2one(string='操作人', comodel_name='res.users', default=lambda self: self.env.user, copy=False, readonly=True)

    # 处理省市区选择问题
    province_select = fields.Selection(string='省', selection=province_city_county_selection, copy=False)
    city_select = fields.Selection(string='市', selection=province_city_county_selection, copy=False)
    county_select = fields.Selection(string='区', selection=province_city_county_selection, copy=False)
    # 导入EXCEL文件
    # xlsx_data = fields.Binary('EXCEL/CSV文件')
    # xlsx_name = fields.Char('名称')

    # 导入CSV文件
    csv_data = fields.Binary('CSV文件')

    csv_name = fields.Char('名称')

    def validate_data(self):
        if not self.province_select:
            raise UserError('省必须选择！')
        if not self.city_select:
            raise UserError('市必须选择！')
        dict_data = {"province_name": self.province_select, "city_name": self.city_select, "county_name": self.county_select}
        return dict_data

    def read_csv(self):
        """
        读取csv
        @return csv_reader解析好的文件，headers表头
        """
        if self.csv_data:
            file_content = base64.b64decode(self.csv_data)
            file_content = StringIO(file_content.decode("utf-8"))
            csv_reader = csv.reader(file_content, delimiter=',')
            headers = next(csv_reader, None)  # 获取表头
            return csv_reader, headers
        else:
            raise UserError('请先上传必要的CSV文件！')

    def action_for_csv_import_postal_code(self):
        """ csv文件导入，获取邮编 """
        csv_reader, headers = self.read_csv()
        Deal1.csv_import_for_spain_postal_code(self.env, csv_reader, headers)

    def action_for_spain_city_combine(self):
        """ 处理西班牙市区由于为区分重音辅音导致的重复数据 """
        Deal1.spain_city_combine(self.env)

    def action_for_spain_county_combine(self):
        """ 处理西班牙区县由于为区分重音辅音导致的重复数据 """
        Deal1.spain_county_combine(self.env)

    def action_for_spain_city_ElxElche(self):
        """ 处理西班牙邮编Elx-Elche城市重复问题 """
        Deal1.spain_city_ElxElche(self.env)

    def action_for_unlink_province(self):
        """ 清掉除西班牙外所有省份 """
        Deal1.unlink_province(self.env)

    def action_for_import_for_europe_postal_code(self):
        """ 欧盟27国邮编导入，除西班牙 """
        csv_reader, headers = self.read_csv()
        Deal1.csv_import_for_europe_postal_code(self.env, csv_reader, headers)

    def action_for_csv_import_country_data(self):
        csv_reader, headers = self.read_csv()
        Deal2.csv_import_for_country__data(self.env, csv_reader, headers)

    def action_for_csv_import_state_city_county_code(self):
        dict_data = self.validate_data()
        csv_reader, headers = self.read_csv()
        Deal2.csv_import_for_state__city_county_code(self.env, csv_reader, headers, dict_data)

    # def read_excel(self):
    #     """读取excel"""
    #     file_data = base64.b64decode(self.csv_data)
    #     wb = xlrd.open_workbook(file_contents=file_data)
    #     sheet = wb.sheet_by_index(0)
    #     for i in range(1, sheet.nrows):
    #         row = sheet.row_values(i)
    #         stripped_row = [isinstance(i, str) and i.strip() or i for i in row]
    #         yield stripped_row
    #
    # def xlsx_import(self):
    #     """ excel导入 """
    #     lines = []
    #     for rcd in self.read_excel():
    #         print(rcd)
